<template>
  <view class='productList'>
    <view class="payInfo" :style="{
            background: themConfig.theme.color
          }">
      <view class="payAmount">
        <text>¥</text>
        <text class="money">{{ payInfo.amount }}</text>
      </view>
      <view>
        <text>{{ payInfo.body }}</text>
      </view>
      <view clss="grip">
        <uv-gap height="70" bgColor=""></uv-gap>
      </view>
    </view>


    <view class="payMethod">
      <uv-radio-group
          placement="column"
          v-model="payRequest.payChannel"
          iconPlacement="right">

        <view class="payMethodWrapper">
          <view class="selectpaymethod">
            <view style="margin-bottom: 10px">选择支付方式</view>
            <uv-line/>
          </view>

          <view class="pay-line" @click="checkPaymentMethod(pay)" v-for="pay in paymentMethod">
            <view class="pay-icon">
              <view>
                <image :src="pay.icon" style="width: 30px;height: 30px"/>
              </view>
              <view class="pay-channelname">{{ pay.channelName }}</view>
            </view>
            <view>
              <uv-radio @change="checkPaymentMethod(pay)" :size="25" :iconSize="22" :activeColor="themConfig.theme.color"
                        :name="pay.payChannel">
              </uv-radio>
            </view>
          </view>
        </view>
      </uv-radio-group>
    </view>


    <uv-transition
        :show="paySuccess"
        :custom-style="{'width':'100%'}"
        :duration="1000"
        fade="zoom-in">
      <view class="paySuccess">
        <image src="https://minio.thisforyou.cn:1443/test/支付成功.png" style="width: 50px;height: 50px"/>
        <view>支付成功</view>
      </view>
    </uv-transition>


    <view class="payBtn" v-if="!paySuccess">
      <view style="width: 100%">
        <uv-button :disabled="payDisabled" @click="toPay" text="确认支付"
                   :color="btnColor()"></uv-button>
      </view>
    </view>

    <view class="payBtn" v-else>
      <view style="width: 100%">
        <uv-button @click="goBack('/pages/index/index')" text="去首页"
                   :color="btnColor()"></uv-button>
      </view>
      <view style="width: 10%"></view>
      <view style="width: 100%">
        <uv-button @click="goBack('/pages/users/order_list/index')" text="查看订单"
                   :color="btnColor()"></uv-button>
      </view>

    </view>

    <view v-if="payInfoTipShow">
      <uv-empty mode="order" text="缺少支付信息" icon="http://cdn.uviewui.com/uview/empty/order.png"></uv-empty>
      <view class="tips">
        <p>支付商品: body</p>
        <p>支付金额: amount</p>
        <p>支付单号: outTradeNo</p>
      </view>
    </view>
  </view>
</template>

<script>
import StatusNav from '@/components/school/statusNav';
import OrderList from '@/components/school/orderList';
import {mapGetters} from "vuex";
import diyJson from '@/config/diy.js';
import * as InfraApi from '@/api/infra.js'
import * as PayChannelApi from '@/api/pay/channel.js'
import * as Utils from '@/utils/util'
import {BASE_CONFIG} from "@/config/app";

// #ifdef H5
let wx = require('jweixin-module');
// #endif
const app = getApp();

export default {
  computed: mapGetters(['uid', 'openId']),
  components: {
    StatusNav,
    OrderList,
  },
  data() {
    return {
      themConfig: diyJson.commonStyle,
      payInfoTipShow: false,

      payInfo: {
        // 只要
        onlyPayType: ['wetchat', 'balance'],
        outTradeNo: '', // 支付单号
        body: '华为mate60 pro',  // 支付商品
        amount: 0,  // 支付金额
        payScene: 'ORDER',  // 支付场景
        payCallBack: '', // 支付后跳转地址
      },

      paySuccess: false,
      payDisabled: false,
      paymentMethod: [
        // {
        //   sort: 10,
        //   preferred: true,
        //   icon: "https://minio.thisforyou.cn:1443/test/余额支付.png",
        //   tradeType: "balance",
        //   channelName: "余额支付",
        //   payChannel: "balance",
        // },
      ],
      payRequest: {
        payChannel: '',
        payScene: 'ORDER',
        tradeType: '',
        outTradeNo: '',
        amount: 0,
      },
      dataPage: {
        current: 1,
        pages: 1,
        size: 1,
        total: 0,
      },
      urlParams: undefined
    };
  },
  onPullDownRefresh() {

  },
  onLoad: function (options) {
    let urlParams = options.params;
    if (urlParams) {
      urlParams = JSON.parse(decodeURIComponent(urlParams))
      this.urlParams = urlParams;
      this.$store.commit('SET_JUMP_INFO', urlParams);
    }
  },
  onShow() {

    this.dataList();
    let data = this.getPayInfo();
    if (data != null) {
      this.pageInit({payInfo: data});
    } else {
      this.paySuccess = false;
      this.payDisabled = true;
    }
  },

  methods: {
    getPayInfo() {
      let data = undefined;
      if (!this.urlParams) {
        data = this.urlParams;
      }else {
        data = this.$store.state.app.jumpParams;
      }
      console.log("payInfo", data)
      if (data != null) {
        if (typeof data === 'string') {
          data = JSON.parse(data)
        }
        if (data.paySuccess === undefined) {
          data['paySuccess'] = false;
          this.$store.commit('SET_JUMP_INFO', data);
        }
        return data;
      }

      return null;
    },

    pageInit(options) {
      console.log("pay options", options)
      let pay = options.payInfo;
      this.payInfo = options.payInfo;
      this.payRequest.outTradeNo = this.payInfo.outTradeNo
      this.payRequest.payScene = this.payInfo.payScene
      if (pay.paySuccess) {
        this.paySuccess = true;
        this.payDisabled = true;
        this.statusNavProperties.setStyle.enableBack = false;
      }
    },

    // 获取支付渠道
    async dataList() {
      let clientType = Utils.getTerminal();
      console.log("clientType", clientType)
      return new Promise((resolve, reject) => {
        PayChannelApi.getEnableChannelCodeList({"clientType": clientType}).then(res => {
          this.paymentMethod = res.data;
          for (let i = 0; i < res.data.length; i++) {
            if (res.data[i].preferred) {
              this.payRequest.payChannel = res.data[i].payChannel
              this.payRequest.tradeType = res.data[i].tradeType
              break;
            }
          }
          this.payRequest.payChannel = this.paymentMethod[0].payChannel
        })
      })
    },

    toPay() {

      if (this.payDisabled) {
        return;
      }
      this.payDisabled = true;
      this.payRequest.outTradeNo = this.payInfo.outTradeNo;
      this.payRequest.amount = this.payInfo.amount;
      this.payRequest.payScene = this.payInfo.payScene;
      this.payRequest.payDesc = this.payInfo.body;
      this.payRequest.payClient = Utils.getTerminal();
      if (this.payRequest.tradeType === 'WX_JSAPI') {
        let metaDataData = {
          wechatMeta: {
            openId: this.openId,
            appId: BASE_CONFIG.appId
          }
        }
        this.payRequest['metaData'] = metaDataData;
      }

      uni.showLoading({
        title: '支付中...',
        mask: true, // 是否显示透明蒙层，防止触摸穿透
      });
      InfraApi.payRequest(this.payRequest).then(res => {
        uni.hideLoading();
        if (res.code === 200 || res.code === 0) {
          if (!res.data.resultAsync) {
            this.paySuccess = true;
            this.setPaySuccess();
          } else {
            this.payDisabled = true;

            // 获取支付渠道
            let queReq = {outTradeNo: this.payInfo.outTradeNo, payChannel: this.payRequest.payChannel}

            // 微信支付
            // JSAPI
            if ("WX_JSAPI" === res.data.tradeType) {

              let that = this;
              let payData = res.data.payInfo.data;

              // #ifdef H5
              wx.config({
                debug: false,  // 开启调试
                appId: payData.appId,
                timestamp: payData.timeStamp,
                nonceStr: payData.nonceStr,
                signature: payData.paySign,
                jsApiList: ['chooseWXPay']
              });
              wx.ready(function () {
                wx.chooseWXPay({
                  timestamp: payData.timeStamp,
                  nonceStr: payData.nonceStr,
                  package: payData.package,  // 预支付ID
                  signType: 'RSA',  // 签名方式
                  paySign: payData.paySign,  // 支付签名
                  success: function (res) {
                    console.log('支付成功', res);
                    uni.showLoading({
                      title: '获取支付结果中...',
                      mask: true, // 是否显示透明蒙层，防止触摸穿透
                    });

                    that.getPayResult(queReq, 10).then((res => {
                      if (res.data.state === 1) {
                        that.paySuccess = true;
                        uni.hideLoading();
                        that.setPaySuccess();
                      }
                    })).catch(res => {
                      uni.hideLoading();
                      that.payDisabled = false;
                    });
                  },
                  fail: function (err) {
                    console.log('支付失败', err);
                    uni.hideLoading();
                    that.payDisabled = false;
                    uni.showToast({
                      icon: 'none',
                      title: '支付/取消失败',
                      duration: 3000
                    });
                  }
                });
              });
              // #endif

              // #ifdef MP
              uni.requestPayment({
                provider: 'wxpay',
                timeStamp: payData.timeStamp,
                nonceStr: payData.nonceStr,
                package: payData.package,
                signType: 'RSA',
                paySign: payData.paySign,
                success: function (res) {
                  uni.showLoading({
                    title: '获取支付结果中...',
                    mask: true, // 是否显示透明蒙层，防止触摸穿透
                  });
                  that.getPayResult(queReq, 10).then((res => {
                    if (res.data.state === 1) {
                      that.paySuccess = true;
                      uni.hideLoading();
                      that.setPaySuccess();
                    }
                  })).catch(res => {
                    uni.hideLoading();
                    that.payDisabled = false;
                  });
                },
                fail: function (err) {
                  // {"errMsg": "requestPayment:fail cancel"}
                  console.log('支付失败', err);
                  uni.hideLoading();
                  that.payDisabled = false;
                  let error = err.errMsg;
                  if (error.indexOf('cancel')>0){
                    uni.showToast({
                      icon: 'none',
                      title: '支付取消',
                      duration:2000
                    });
                  }
                }
              });
              // #endif
              return;
            }

            uni.showLoading({
              title: '获取支付结果中...',
              mask: true, // 是否显示透明蒙层，防止触摸穿透
            });

            this.getPayResult(queReq, 10).then((res => {
              if (res.data.state === 1) {
                this.paySuccess = true;
                uni.hideLoading();
                this.setPaySuccess();
              }
            })).catch(res => {
              uni.hideLoading();
              this.payDisabled = false;
            });
          }
        } else {
          this.payDisabled = false;
        }
      }).catch(e => {
        this.payDisabled = false;
        uni.hideLoading();
      })
    },

    async getPayResult(params, retryCount) {
      return new Promise((resolve, reject) => {
        PayChannelApi.queryPayResult(params)
        .then(res => {
          if (res.data.state !== 1 && retryCount > 0) {
            setTimeout(() => {
              this.getPayResult(params, retryCount - 1)
              .then(resolve).catch(reject)
            }, 1000);
          } else {
            resolve(res);
          }
        }).catch(res => {
          reject()
        })
      })
    },

    setPaySuccess() {
      let payInfo = this.getPayInfo();
      if (payInfo !== null) {
        payInfo.paySuccess = true;
        this.statusNavProperties.setStyle.enableBack = false;
        this.$store.commit('SET_JUMP_INFO', payInfo);
        // setTimeout(()=>{
        //   window.location.href = window.location.href+'&time=1'
        // },1000)
      }
    },

    checkPaymentMethod(pay) {
      console.log("pay", pay);
      this.payRequest.payChannel = pay.payChannel;
      this.payRequest.tradeType = pay.tradeType;
    },

    goBack(url) {
      this.$store.commit('SET_JUMP_INFO', null);
      this.paySuccess = false;

      if (url) {
        if (url === '/pages/index/index') {
          app.globalData.tabBarIndex = 0;
          uni.$emit("tabBarIndexChange", 0);
          this.$store.commit('SET_TAB_BAR_IDX', 0);
          return uni.switchTab({
            url: url,
          })
        }
        return uni.redirectTo({
          url: url,
        })
      } else {
        // #ifdef H5
        return history.back();
        // #endif
        // #ifndef H5
        return uni.navigateBack({
          delta: 1,
        })
        // #endif
      }
    },

    btnColor() {
      return 'linear-gradient(to right,' + this.themConfig.theme.subColor + ',' + this.themConfig.theme.color + ')'
      // return' linear-gradient(to right, rgb(66, 83, 216), rgb(213, 51, 186))';
    },
    getApp() {
      return app;
    },

  },
  onReachBottom() {
  }
}
</script>

<style scoped lang="scss">
.payInfo {
  height: 300rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: white;
  border-radius: 0 0 15px 15px;

  .money {
    font-size: 50px;
    color: white;
    margin-left: 5px;
  }
}

.payMethod {
  padding: 0 15px;
}

.payMethodWrapper {
  border-radius: 10px;
  background: white;
  padding: 20px;
  position: relative;
  top: -60px
}

.pay-line {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .pay-icon {
    display: flex;
    align-items: center;
    height: 60px;
  }

  .pay-channelname {
    margin-left: 10px;
  }
}

.selectpaymethod {
  margin-bottom: 10px;
}

.tips {
  margin-top: 20px;
  text-align: center;
  line-height: 30px;
  color: #909399;
}

.paySuccess {
  display: flex;
  justify-content: center;
  position: relative;
  top: -30px;
  align-items: center;

  view {
    margin-left: 20px;
    color: #12c122;
    font-size: 30px;
  }
}

.payBtn {
  padding: 0 15px;
  display: flex;
  width: 100%;
}
</style>
